package com.gengzp.mq.common.utils;

/**
 * @ClassName SnowFlakeIdUtil
 * @Description 雪花算法id工具类
 * @Author gengzp
 * @Date 2025/6/8 13:27
 */
public class GengzpMqSnowflakeIdUtils {
    // 起始时间戳（2020-01-01）
    private final static long START_TIMESTAMP = 1577836800000L;

    // 各部分占用的位数
    private final static long WORKER_ID_BITS = 5L;     // 工作机器ID位数
    private final static long DATACENTER_ID_BITS = 5L; // 数据中心ID位数
    private final static long SEQUENCE_BITS = 12L;     // 序列号位数

    // 各部分的最大值
    private final static long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS); // 31
    private final static long MAX_DATACENTER_ID = -1L ^ (-1L << DATACENTER_ID_BITS); // 31

    // 各部分向左的位移
    private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private final static long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private final static long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    // 序列号掩码（4095）
    private final static long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);

    // 工作机器ID和数据中心ID
    private final long workerId;
    private final long datacenterId;

    // 序列号和上次时间戳
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    // 静态单例
    private static GengzpMqSnowflakeIdUtils instance;

    static {
        // 默认初始化，使用0作为workerId和datacenterId
        init(0, 0);
    }

    /**
     * 初始化ID生成器
     *
     * @param workerId     工作机器ID (0-31)
     * @param datacenterId 数据中心ID (0-31)
     */
    public static synchronized void init(long workerId, long datacenterId) {
        if (instance == null) {
            instance = new GengzpMqSnowflakeIdUtils(workerId, datacenterId);
        }
    }

    /**
     * 私有构造函数
     */
    private GengzpMqSnowflakeIdUtils(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID 不能大于 " + MAX_WORKER_ID + " 或小于 0");
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("数据中心 ID 不能大于 " + MAX_DATACENTER_ID + " 或小于 0");
        }

        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    /**
     * 生成下一个唯一ID
     */
    public static synchronized long nextId() {
        return instance.generateId();
    }

    /**
     * 生成下一个唯一ID（字符串形式）
     */
    public static synchronized String nextIdStr() {
        return String.valueOf(instance.generateId());
    }

    /**
     * 实际生成ID的方法
     */
    private synchronized long generateId() {
        long currentTimestamp = System.currentTimeMillis();

        // 处理时钟回拨
        if (currentTimestamp < lastTimestamp) {
            // 容忍200毫秒的时钟回拨
            if (lastTimestamp - currentTimestamp < 200) {
                // 等待时钟恢复
                currentTimestamp = waitForNextMillis(lastTimestamp);
            } else {
                throw new RuntimeException("时钟回拨超过200毫秒，拒绝生成ID " + (lastTimestamp - currentTimestamp) + " 毫秒");
            }
        }

        if (currentTimestamp == lastTimestamp) {
            // 同一毫秒内，序列号自增
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                // 序列号用尽，等待下一毫秒
                currentTimestamp = waitForNextMillis(lastTimestamp);
            }
        } else {
            // 不同毫秒，重置序列号
            sequence = 0L;
        }

        lastTimestamp = currentTimestamp;

        // 按规则组装ID
        return ((currentTimestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT) |
                (datacenterId << DATACENTER_ID_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                sequence;
    }

    /**
     * 等待下一毫秒
     */
    private long waitForNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    /**
     * 从ID中解析出时间戳
     */
    public static long extractTimestamp(long id) {
        return (id >> TIMESTAMP_SHIFT) + START_TIMESTAMP;
    }

    /**
     * 从ID中解析出工作机器ID
     */
    public static long extractWorkerId(long id) {
        return (id >> WORKER_ID_SHIFT) & MAX_WORKER_ID;
    }

    /**
     * 从ID中解析出数据中心ID
     */
    public static long extractDatacenterId(long id) {
        return (id >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID;
    }

    /**
     * 从ID中解析出序列号
     */
    public static long extractSequence(long id) {
        return id & SEQUENCE_MASK;
    }
}